package cn.bupt.adt.util;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ScheduledThreadPoolExecutor;

import cn.bupt.adt.constant.Constants;
import cn.bupt.adt.entity.autogenerate.DoctorAppUser;
import cn.bupt.adt.entity.autogenerate.Order;
import cn.bupt.adt.service.IDoctorService;
import cn.bupt.adt.service.IOrderService;

public class MyTask implements Runnable {
	DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	Date date;
	ScheduledThreadPoolExecutor timer;
	int orderId;
	IOrderService orderService;
	IDoctorService doctorService;
	/**
	 * 
	 * @param date 发单时刻
	 * @param timer 定时器 ，传入是为了能让自己停下
	 * @param orderService
	 * @param orderId 订单id
	 * @param doctorService
	 */
	public MyTask(Date date,ScheduledThreadPoolExecutor timer,
			IOrderService orderService,int orderId,IDoctorService doctorService){
		this.date = date;
		this.timer = timer;
		this.orderService = orderService;
		this.orderId = orderId;
		this.doctorService = doctorService;
	}//13240266126 Doc+-6799
	@Override
	public void run() {
		System.out.println(orderId);
		Order order = orderService.getOrderById(orderId);
		if(!order.getStatus().equals(Constants.ORDER_STATUS_UNTAKED)) {
			timer.shutdown();
		}
		else {
			int diff = (int )((new Date().getTime() - this.date.getTime())/1000/60);
			if(diff < 1) {
				System.out.println("刚发布");
				//更新订单状态
				order.setPublishStatus(Constants.BFFORE10MIN);
				orderService.updateOrderByPrimarykeySelective(order);
				//获取符合接单条件的医生
				List<DoctorAppUser> lists = doctorService.getDoctorsByOrder(order);
				System.out.println("符合接单条件的医生数量："+lists.size());
				if(lists.isEmpty())
					return ;
				Collections.sort(lists);
				//给前50%的医生发短信通知接单
				SendSMSUtil sendSms = new SendSMSUtil();
				int num = (lists.size() >> 1);
				for(int i = 0 ; i<num;i++)
					sendSms.SendSMS(lists.get(i).getPhone(), new String[]{"0-10分钟，前50%的人收短信"}, Constants.SMS_JIEDAN);
			}
			else {
				if(diff >= 1 && diff < 2) {
					System.out.println("10-20分钟");
					//更新订单状态
					order.setPublishStatus(Constants.BETWEEN10AND20);
					orderService.updateOrderByPrimarykeySelective(order);
					//获取符合接单条件的医生
					List<DoctorAppUser> lists = doctorService.getDoctorsByOrder(order);
					if(lists.isEmpty())
						return ;
					//给所有医生发短信通知接单
					SendSMSUtil sendSms = new SendSMSUtil();
					for(DoctorAppUser d:lists)
						sendSms.SendSMS(d.getPhone(), new String[]{"10-20分钟，所有的人收短信"}, Constants.SMS_JIEDAN);
					
				}
				else {
					System.out.println(">20分钟");
					//更新订单状态，变为超时订单
					order.setPublishStatus(Constants.OVER20);
					orderService.updateOrderByPrimarykeySelective(order);
					timer.shutdown();
				}
			}
		}
	}

}
